#include <dbg.h>

#include <cassert>
#include <climits>
#include <numeric>

using namespace std;

class Solution {
public:
    int minOperations(vector<int>& nums, int x) {
        int res = INT_MAX;
        int left = 0;
        int n = nums.size();
        int sum = accumulate(nums.begin(), nums.end(), 0);
        for (int right = 0; right < n; ++right) {
            sum -= nums[right];
            while (sum < x && left <= right) {
                sum += nums[left];
                ++left;
            }
            if (sum == x) {
                res = min(res, n - right + left - 1);
            }
        }
        return res == INT_MAX ? -1 : res;
    }
};

int main() {
    Solution s;

    vector<int> nums1 = {1, 1, 4, 2, 3};
    vector<int> nums2 = {5, 6, 7, 8, 9};
    vector<int> nums3 = {3, 2, 20, 1, 1, 3};

    int x1 = 5;
    int x2 = 4;
    int x3 = 10;

    assert(s.minOperations(nums1, x1) == 2);
    assert(s.minOperations(nums2, x2) == -1);
    assert(s.minOperations(nums3, x3) == 5);

    return 0;
}